package com.example.demo.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.example.demo.configuration.AliReturnPay;
import com.example.demo.configuration.WebSocket;
import com.example.demo.controller.bean.Result;
import com.example.demo.dto.CouponMonitorDTO;
import com.example.demo.mapper.entity.AdTransaction;
import com.example.demo.mapper.entity.Clothing;
import com.example.demo.service.AdWalletService;
import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

@RequestMapping("adWallet")
@Api(value = "商家钱包管理接口", tags = {"商家钱包管理接口"})
@RestController
@Slf4j
public class AdWalletController {
    @Autowired
    private AdWalletService service;
    @Autowired
    private WebSocket webSocket;	// 导入刚刚写好的 WebSocket 工具类
    // 支付宝网关：沙箱环境 (真实环境的话改外：https://openapi.alipay.com/gateway.do)
    private static final String URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // APPID (请自行填写，真实环境请做对应修改)
    private static final String APP_ID = "9021000135632657";
    // 应用私钥 (请自行填写，真实环境请做对应修改)
    private static final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDGBcRWpznpm8cckZ5CL8IGLaQWCZcd2dN9FK5oCaMj35Ol5AxxQylirBkSoxcfK5haT1f4O2T7Vr5VzqDHwY7r5lMR+HTq+fkx6coi3vVX5f+m5gKvB3tv0IZKnDjSQI/c7jdmRRk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NLaiZcBmBaQFwKBgHy2LIrXO+chgFfVAzYNtr38Pq60VTW1chcCkMWsL/Fk2TeNh3buwkXgKUzt5cXZZInDX1KXtHu0FbLyo5C6fBW9VB4uPfTgKGDJYeWk1gk7wf5O889BLrjvArhkyCNtMNi7WLoQhOPfafIV5o94BVK2TH6k9YFP/s3pJmWR4QmxAoGASfwqSIu+kPk45FzQwtzVE47MGOaXMgkbFwMAtzPbJF1QfxTCIRVC2c4RRh0GUg6c2eBjIM32in7TT0baL1us1+z1DBRCAex9gk7f99aqVDDKorvoKyRjIOjoIvXStynfT4h2mGKe/WzdLD0qCKqbqAoeDwDSsUDYmHxGPiQ4+9k=";
    // 数据返回的格式 (只支持json格式)
    private static final String FORMAT = "json";
    // 验签编码 (根据需要修改)
    private static final String CHARSET = "UTF-8";
    // 支付宝公钥 (请自行填写，真实环境请做对应修改)
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh/XZCvrOs6L5iiURX8OD1R/NGEwpb5pDx5NMO+cHFy7/81zS0l954sUFcXIgL6fVg4e2SkXVmSaX1UFriSyz9j0055Klu6W5z8mrPULHJlUunCuIECk+92L14Jzn5iiRMtILHTlQdTPta4mYQm4vlp++BXMjRnojAgBxOxyZ1r+WTnBeTnQHLpTPA0kMjuml4HX10yNqEeEwZ99Fe+JOdrceblwJ9Ad7dFBWjZ1RSp4HfZrZSX+Pgx7UbS7mOgXyszwd4dxi4SzMdoImsWV09nJUMZajOqvawdLd4DS+Nw1ByP1pJGIJ3HXgUjla48MjVkKgAL0uBlNXx6g4WhzP9QIDAQAB";
    // 验签加密方法 (根据需要修改)
    private static final String SIGN_TYPE = "RSA2";

    @ResponseBody
    @ApiOperation(value = "获取当前账户余额")
    @RequestMapping(value = "getRemainingSum", method = {RequestMethod.POST})
    public SaResult getRemainingSum() {
        System.out.println("获取当前账户余额");
        if (StpUtil.getLoginIdDefaultNull() != null) {
            // 获取当前会话账号id, 如果未登录，则返回 null
            int userId = StpUtil.getLoginIdAsInt();
            double remainingSum = service.selectRemainingSum(userId);
            return SaResult.data(remainingSum);
        } else {
            return SaResult.error("未登录");
        }
    }

    @ApiOperation(value = "支付宝支付 沙箱环境")
    @PostMapping("/sandboxPay/{totalAmount}")
    public Object sandboxPay(@PathVariable("totalAmount")Double totalAmount) throws AlipayApiException {
        System.out.println("支付宝支付 沙箱环境");
        System.out.println("充值金额："+totalAmount);

        int advertiserId = StpUtil.getLoginIdAsInt();
        System.out.println("advertiserId:"+advertiserId);
        String outTradeNo = UUID.randomUUID().toString().substring(0,12);  // 生成八位随机数作为订单号

        AdTransaction transaction = new AdTransaction();
        transaction.setAmount(totalAmount);
        transaction.setOutTradeNo(outTradeNo);
        transaction.setAdvertiserId(advertiserId);
        transaction.setTransactionType(1);
        service.setAliRequestPay(transaction);

        AlipayClient alipayClient = new DefaultAlipayClient(URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);
        AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
        // 设置支付宝异步通知回调地址 (注意：这个网址必须是可以通过外网访问的网址)
        alipayRequest.setNotifyUrl("http://i7aku8.natappfree.cc/adWallet/call");
        alipayRequest.setBizContent ( "{"   +
                "\"out_trade_no\":\"" + outTradeNo + "\"," + // 商户订单号
                "\"total_amount\":\"" + totalAmount + "\"," +	// 充值金额
                "\"subject\":\"新苗同学广告主余额充值\"," +	// 商品标题
                "\"store_id\":\"新苗同学后台管理系统\"," +	// 组织或公司名
                "\"timeout_express\":\"90m\"}" );	// 订单有效时间
        AlipayTradePrecreateResponse response = alipayClient.execute (alipayRequest);
        // 返回支付宝支付网址，用于生成二维码
        String qr = response.getQrCode();
        System.out.println("生成二维码:"+qr);
        return response;
    }

    @ApiOperation(value = "支付宝支付 异步通知")
    @PostMapping("/call")
    public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPay aliReturnPay) throws IOException {
        // 通知返回的数据会封装到 AliReturnPay 类中
        response.setContentType("type=text/html;charset=UTF-8");
        System.out.println("支付宝支付 异步通知");
        System.out.println("通知返回的数据："+aliReturnPay);

        service.setAliReturnPay(aliReturnPay);
        // 支付成功返回码
        if (("TRADE_SUCCESS").equals(aliReturnPay.getTrade_status())){
            // 向前端发送一条支付成功的通知
            webSocket.sendMessage("true");
        }
    }

    @ResponseBody
    @ApiOperation(value = "获取充值记录列表接口")
    @RequestMapping(value = "getAdTransactionList", method = {RequestMethod.POST})
    public Result<PageVo<AdTransaction>> getAdTransactionList(@RequestBody PageBo pageBo) {
        int userId = StpUtil.getLoginIdAsInt();
        int advertiserId = service.selectAdvertiser(userId);
        PageVo<AdTransaction> list = service.getAdTransactionList(pageBo, advertiserId);
        return Result.ok(list);
    }
}
